/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2023-03-10 16:16:46
 */

import { createContext, useContext, useReducer } from 'react';
import {
  SET_TITLE,
  SET_SELECT_AT,
  SET_SELECT_FOND_ID,
  SET_SELECT_AT_ID,
  SET_CONDITION,
  SET_FIELDCONDITION,
  SET_ADDITIONALSEARCH,
  SET_LISTQUERYDATA,
  SET_CHOICE
} from '../constants';
import { SearchResultReducer } from '../reducers/SearchResultReducer';

const SearchResultContext = createContext();

const initialState = {
  title: '',
  atConditionList: {},
  fieldConditionList: [],
  additionalSearch: {},
  listQueryData: [],
  choices: {},
  levelList: [
    { id: 0, value: '组件级' },
    { id: 1, value: '文件级' },
    { id: 2, value: '案卷级' },
    { id: 3, value: '项目级' }
  ]
};

const SearchResultContextProvider = (props) => {
  const [state, dispatch] = useReducer(SearchResultReducer, initialState);

  const actions = {
    /**
     * @description: 获取和传出限定条件
     */
    getCondition(data) {
      console.log('context', data);
      dispatch({ type: SET_CONDITION, data });
    },
    getFieldConditionList(data) {
      dispatch({ type: SET_FIELDCONDITION, data });
    },
    // 整体赋值
    setAdditionalSearch(data) {
      dispatch({ type: SET_ADDITIONALSEARCH, data });
    },
    // 页码切换赋值
    getListQueryData(data) {
      dispatch({ type: SET_LISTQUERYDATA, data });
    },
    //
    setChoice(data) {
      console.log('12111');
      dispatch({ type: SET_CHOICE, data });
    },
    /**
     * @description: 设置搜索结果标题
     */
    setTitle(title) {
      dispatch({ type: SET_TITLE, title });
    },
    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的全宗
     */
    setSelectFondId(id) {
      dispatch({ type: SET_SELECT_FOND_ID, id });
    },

    /**
     * @description: 设置选中的档案类型ID
     */
    setSelectATId(id) {
      dispatch({ type: SET_SELECT_AT_ID, id });
    }
  };
  const filters = {
    levelFilter(id) {
      return state.levelList.find((item) => item.id === id)?.value || '-';
    }
  };
  return (
    <SearchResultContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </SearchResultContext.Provider>
  );
};

export const useSearchResultContext = () => {
  return useContext(SearchResultContext);
};

export { SearchResultContext, SearchResultContextProvider };
